/*
   Copyright (C) 2009 Xizhi Zhu.  All Rights Reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "p2p-app.h"
#include "p2p-packet.h"
#include "p2p-param.h"

static class P2PAppClass : public TclClass
{
public:
    P2PAppClass() : TclClass("Application/P2P/App") {}
    TclObject* create(int argc, const char*const* argv)
    {
        return (new P2PApp((Node*)TclObject::lookup(argv[4])));
    }
} class_p2p_app;

P2PApp::P2PApp(Node* node)
    : RealApplication(node), current_downloading_links_(0)
{
    connectionCheckTimer_ = new ConnectionCheckTimer(this);

    // set all chunks as not available
    chunks_.resize(P2P_CHUNK_NUMBER);
    for (int i = 0; i < P2P_CHUNK_NUMBER; i++)
    {
        chunks_[i].available_ = P2P_CHUNK_NOT_AVAILABLE;
    }
}

P2PApp::~P2PApp()
{
    delete connectionCheckTimer_;
}

void P2PApp::recv(ADU* packet, nsaddr_t src)
{
    P2PPacket* p = (P2PPacket*)packet;

    switch (p->type_)
    {
        case PktTypeRegReply:
            // successfully registered at the tracker
            connectionCheckTimer_->resched(0.0);
            break;

        case PktTypeNodeListReply:
            // node list received
            handleNodeListReply(p);
            break;

        case PktTypeChunkListRequest:
            // chunk list requested
            handleChunkListRequest(p);
            break;

        case PktTypeChunkListReply:
            // chunk list received
            handleChunkListReply(p);
            break;

        case PktTypeChunkRequest:
            // chunk requested
            handleChunkRequest(p);
            break;

        case PktTypeChunkReply:
            // received chunks
            handleChunkReply(p);
            break;

        default:
            break;
    }

    delete packet;
}

int P2PApp::command(int argc, const char*const* argv)
{
    if (2 == argc)
    {
        if (0 == strcmp(argv[1], "stop"))
        {
            // send the unregistration request to the tracker
            P2PPacket* p = new P2PPacket(PktTypeUnregRequest);
            p->id_ = node_->address();
            p->isServer_ = false;
            send(p, tracker_->getNode()->address());

            return TCL_OK;
        }
    }
    else if (3 == argc)
    {
        if (0 == strcmp(argv[1], "start"))
        {
            // get the tracker
            tracker_ = (P2PTracker*)TclObject::lookup(argv[2]);

            // send registration request to the tracker
            P2PPacket* p = new P2PPacket(PktTypeRegRequest);
            p->id_ = node_->address();
            p->isServer_ = false;
            send(p, tracker_->getNode()->address());

            return TCL_OK;
        }
    }

    return RealApplication::command(argc, argv);
}

// called when ConnectionCheckTimer expires
void P2PApp::checkConnection()
{
    // TODO check if the connection speed is enough
    // do nothing if it's enough

    // request node list from the tracker
    requestNodeList();
}

// request node list
void P2PApp::requestNodeList()
{
    P2PPacket* p = new P2PPacket(PktTypeNodeListRequest);
    p->id_ = node_->address();
    send(p, tracker_->getNode()->address());
}

// called when node list received
void P2PApp::handleNodeListReply(P2PPacket* packet)
{
    // update local node list
    server_list_ = packet->server_list_;
    peer_list_ = packet->peer_list_;

    // remove itself out of the list
    int size = peer_list_.size();
    for (int i = 0; i < size; i++)
    {
        if (node_->address() == peer_list_[i])
        {
            peer_list_.erase(peer_list_.begin() + i);
            break;
        }
    }

    // request chunk list
    requestChunkList();

    // request chunk
    requestChunk();
}

// request chunk list
void P2PApp::requestChunkList()
{
    int size = peer_list_.size();
    nsaddr_t id = node_->address();
    for (int i = 0; i < size; i++)
    {
        P2PPacket* p = new P2PPacket(PktTypeChunkListRequest);
        p->id_ = id;
        send(p, peer_list_[i]);
    }
}

// called when chunk list request received
void P2PApp::handleChunkListRequest(P2PPacket* packet)
{
    P2PPacket* p = new P2PPacket(PktTypeChunkListReply);
    p->id_ = node_->address();
    for (int i = 0; i < P2P_CHUNK_NUMBER; i++)
    {
        if (P2P_CHUNK_AVAILABLE == chunks_[i].available_)
        {
            p->available_chunks_.push_back(i);
        }
    }
    send(p, packet->id_);
}

// called when chunk list received
void P2PApp::handleChunkListReply(P2PPacket* packet)
{
    // add to chunk info
    nsaddr_t src = packet->id_;
    int size = packet->available_chunks_.size();
    for (int i = 0; i < size; i++)
    {
        // check if it's already recorded
        int chunk_id = packet->available_chunks_[i];
        int size2 = chunks_[chunk_id].who_has_.size();
        int j = 0;
        for (j = 0; j < size2; j++)
        {
            if (chunks_[chunk_id].who_has_[j] == src)
            {
                break;
            }
        }
        if (j == size2)
        {
            chunks_[chunk_id].who_has_.push_back(src);
        }
    }

    // request chunks
    requestChunk();
}

// request chunks
void P2PApp::requestChunk()
{
    // TODO request which chunk from which node

    // if current downloading links are too many, do nothing
    if (P2P_MAX_DOWNLOADING_LINKS <= current_downloading_links_)
    {
        return;
    }

    int chunk_id = getNextNeededChunk();
    if (-1 == chunk_id)
    {
        // we have downloaded all available chunks
        return;
    }

    current_downloading_links_++;
    P2PPacket* p = new P2PPacket(PktTypeChunkRequest);
    p->id_ = node_->address();
    p->chunk_request_ = chunk_id;
    nsaddr_t dst;
    if (chunk_id % 2 && chunks_[chunk_id].who_has_.size() > 0)
    {
        dst = chunks_[chunk_id].who_has_[chunk_id % chunks_[chunk_id].who_has_.size()];
    }
    else
    {
        dst = server_list_[0];
    }
    chunks_[chunk_id].available_ = dst;
    send(p, dst);
}

// called when chunks requested
void P2PApp::handleChunkRequest(P2PPacket* packet)
{
    // TODO if we need to respond

    P2PPacket* reply = new P2PPacket(PktTypeChunkReply);
    reply->id_ = node_->address();
    reply->chunk_reply_ = packet->chunk_request_;
    send(reply, packet->id_);
}

// called when chunks received
void P2PApp::handleChunkReply(P2PPacket* packet)
{
    current_downloading_links_--;
    chunks_[packet->chunk_reply_].available_ = P2P_CHUNK_AVAILABLE;

    requestChunk();
}

// get the next chunk needed, return -1 if having all chunks
int P2PApp::getNextNeededChunk()
{
    // TODO which chunk is of highest priority

    int size = chunks_.size();
    for (int i = 0; i < size; i++)
    {
        if (P2P_CHUNK_NOT_AVAILABLE == chunks_[i].available_)
        {
            return i;
        }
    }
    return -1;
}

// timer
ConnectionCheckTimer::ConnectionCheckTimer(P2PApp* app): app_(app)
{
}

void ConnectionCheckTimer::expire(Event*)
{
    app_->checkConnection();
    resched(P2P_CONNECTION_CHECK_INTERVAL);
}

